#!/usr/bin/env python3

#
# $Id: vogon_poetry.py 4 2012-06-29 10:42:48Z xdr.box@gmail.com $
#
# Beautiful Vogan-like random poetry - yet another way for learning English
# Inspired by example from book 'Programming in Python 3' by Mark Summerfield
#
# Alexander Simakov, <xdr (dot) box (at) Google Mail>
# http://alexander-simakov.blogspot.com/
#

import os
import random
import re

CORPUS = os.path.dirname(os.path.realpath(__file__)) + '/corpus';

ARTICLE   = 'article'
ADVERB    = 'adverb'
VERB      = 'verb'
NOUN      = 'noun'
ADJECTIVE = 'adjective'

WORD_TYPES = { ARTICLE, ADVERB, VERB, NOUN, ADJECTIVE }

NUMBER_OF_SENTENCIES = 5

def load_corpus():
    corpus = {}
    for word_type in WORD_TYPES:
        with open(CORPUS + '/' + word_type + 's.txt', 'r') as corpus_file:
            corpus[word_type] = list(map(lambda x: x.rstrip(os.linesep), corpus_file.readlines()))

    return corpus

def is_vowel(letter):
    if letter.lower() in 'aeiou':
        return True
    else:
        return False

def get_random_word(corpus, word_type):
    return random.choice(corpus[word_type])

def get_random_words(corpus, word_types):
    return ' '.join(list(map(lambda x: get_random_word(corpus, x), word_types)))

def get_random_title(corpus):
    return get_random_words(corpus, [ADJECTIVE, NOUN]).capitalize()

def get_random_sentence(corpus):
    sentence_types = [
        [ARTICLE, NOUN, VERB, ADVERB],
        [ARTICLE, NOUN, VERB],
        [ARTICLE, ADJECTIVE, NOUN, VERB],
        [ARTICLE, ADJECTIVE, NOUN, VERB, ADVERB],
    ]

    sentence = get_random_words(corpus, random.choice(sentence_types))

    if sentence.startswith('a ') and is_vowel(sentence[2]):
        sentence = re.sub('^a', 'an', sentence)

    return sentence.capitalize()

def get_random_poem(corpus):
    title = get_random_title(corpus)
    text = map(lambda x: get_random_sentence(corpus), range(NUMBER_OF_SENTENCIES))

    return { 'title': title, 'text': text }

def main():
    corpus = load_corpus()

    poem = get_random_poem(corpus)

    print(poem['title'])
    print()
    print("\n".join(poem['text']))

    return

main()
